package cn.yunhe.java.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;

import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.IOUtils;

import java.io.*;

public class SevenCowUtil {

    private SevenCowUtil(){

    }
    /**
     * 上传文件服务
     * @param is 传入图片输入流
     * @param key 上传成功后文件 name
     * @return 网络图片访问路径
     */
    public static String update2Service(InputStream is, String key) {

        String accessPath = "上传失败！";

        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huabei());

        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);

        //...生成上传凭证，然后准备上传
        String accessKey = "YnXwo2RSm2dnNo-yt0D8rf97K-0JXGwNhQbApWma";
        String secretKey = "E8V9CLnz5BugDEYcSh3leeSVsxDTJ_RfC-Mhmmt3";
        String bucket = "huiminpay-zk";

        try {

            byte[] uploadBytes = IOUtils.toByteArray(is);
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);

            try {
                Response response = uploadManager.put(uploadBytes, key, upToken);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                // 访问路径
                accessPath = "访问路径：http://quw05gujp.hb-bkt.clouddn.com/" + putRet.key;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (UnsupportedEncodingException ex) {
            //ignore
        } catch (IOException e) {
            e.printStackTrace();
        }
        return accessPath;
    }

}
